﻿using System;
using System.IO;
using System.Web;
using System.Collections.Generic;

using E.BLL;
using E.Model;
using E.Enum;
using E.Web.UI.Page;

using X.Common;

namespace E.Web.Teacher.internals.publics.courseware
{
    public partial class Edit : TeacherBasePage
    {
        public Dictionary<int, string> courseList;
        public CourseWareModel model = new CourseWareModel();
        public string act;
        public int id, r_courseid;
        public string se = "0";

        protected override void ShowPage()
        {
            CourseBLL bll = new CourseBLL();
            courseList = bll.GetInternalPublicCourseList();

            id = XRequest.GetInt("id", -1);
            r_courseid = XRequest.GetInt("cid", -1);
            se = XRequest.GetString("se").Equals("") ? "0" : XRequest.GetString("se");
            act = XRequest.GetString("act");
            string oldPicFilePath = XRequest.GetString("o_p_p");
            string oldSoundFilePath = XRequest.GetString("o_s_p");
            string oldVideoFilePath = XRequest.GetString("o_v_p");

            if (ispost)
            {
                int courseid = XRequest.GetInt("CourseSlt", -1);
                int serialNumber = XRequest.GetInt("SerialNumberTxt", -1);
                string content = XRequest.GetString("ContentTxt");
                //string videoUrl = XRequest.GetString("VideoUrlTxt");

                if (CheckValue())
                {
                    model = new CourseWareModel();
                    model.CourseID = courseid;
                    model.SerialNumber = serialNumber;
                    model.Content = Filter(content);
                    //model.VideoUrl = videoUrl;

                    model.ImgUrl = "";
                    model.SoundUrl = "";
                    model.VideoUrl = "";
                    HttpPostedFile picFile = HttpContext.Current.Request.Files["PicFileUpload"];
                    HttpPostedFile soundFile = HttpContext.Current.Request.Files["SoundFileUpload"];
                    HttpPostedFile videoFile = HttpContext.Current.Request.Files["VideoFileUpload"];

                    string host = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
                    string picFilePath = "";
                    string soundFilePath = "";
                    string videoFilePath = "";
                    bool fileErr = false;
                    bool hasFile = false;
                    string serverPath = System.Web.HttpContext.Current.Server.MapPath("/");

                    string msg = "";

                    #region file handle
                    
                    #region pic

                    if (picFile.ContentLength > 0)
                    {
                        if (picFile.ContentLength < config.FileUpLoadMaxLength && !picFile.FileName.ToLower().Equals(soundFile.FileName.ToLower()))
                        {
                            hasFile = true;
                            string fullName = picFile.FileName;
                            string fileName = fullName;
                            if (fullName.IndexOf('\\') != -1)
                            {
                                fileName = fullName.Substring(fullName.LastIndexOf('\\') + 1);
                            }
                            picFilePath = "upload\\courseware\\pic\\" + fileName;

                            string scheme = HttpContext.Current.Request.Url.Scheme;
                            model.ImgUrl = scheme + "://" + host + "/upload/courseware/pic/" + fileName;

                            if (File.Exists(serverPath + picFilePath))
                            {
                                fileErr = true;
                                msg = "文件已经存在";
                            }
                            else
                            {
                                try
                                {
                                    picFile.SaveAs(serverPath + picFilePath);
                                }
                                catch (IOException IoEx)
                                {
                                    fileErr = true;
                                    msg = IoEx.Message;
                                }
                                catch (Exception ex)
                                {
                                    fileErr = true;
                                    msg = ex.Message;
                                }
                            }
                        }
                        else
                        {
                            fileErr = true;
                            msg = "文件错误";
                        }
                    }

                    #endregion

                    #region sound

                    if (soundFile.ContentLength > 0)
                    {
                        if (soundFile.ContentLength < config.FileUpLoadMaxLength && !picFile.FileName.ToLower().Equals(soundFile.FileName.ToLower()))
                        {
                            hasFile = true;
                            string fullName = soundFile.FileName;
                            string fileName = fullName;
                            if (fullName.IndexOf('\\') != -1)
                            {
                                fileName = fullName.Substring(fullName.LastIndexOf('\\') + 1);
                            }
                            soundFilePath = "upload\\courseware\\sound\\" + fileName;

                            string scheme = HttpContext.Current.Request.Url.Scheme;
                            model.SoundUrl = scheme + "://" + host + "/upload/courseware/sound/" + fileName;

                            if (File.Exists(serverPath + soundFilePath))
                            {
                                fileErr = true;
                                msg = "文件已经存在";
                            }
                            else
                            {
                                try
                                {
                                    soundFile.SaveAs(serverPath + soundFilePath);
                                }
                                catch (IOException IoEx)
                                {
                                    fileErr = true;
                                    msg = IoEx.Message;
                                }
                                catch (Exception ex)
                                {
                                    fileErr = true;
                                    msg = ex.Message;
                                }
                            }
                        }
                        else
                        {
                            fileErr = true;
                            msg = "文件错误";
                        }
                    }

                    #endregion

                    #region video

                    if (videoFile.ContentLength > 0)
                    {
                        if (videoFile.ContentLength < config.VideoFileMaxLength)
                        {
                            hasFile = true;
                            string fullName = soundFile.FileName;
                            string fileName = fullName;
                            if (fullName.IndexOf('\\') != -1)
                            {
                                fileName = fullName.Substring(fullName.LastIndexOf('\\') + 1);
                            }
                            videoFilePath = "upload\\courseware\\v\\" + fileName;

                            string scheme = HttpContext.Current.Request.Url.Scheme;
                            model.VideoUrl = scheme + "://" + host + "/upload/courseware/v/" + fileName;

                            if (File.Exists(serverPath + soundFilePath))
                            {
                                fileErr = true;
                                msg = "文件已经存在";
                            }
                            else
                            {
                                try
                                {
                                    videoFile.SaveAs(serverPath + soundFilePath);
                                }
                                catch (IOException IoEx)
                                {
                                    fileErr = true;
                                    msg = IoEx.Message;
                                }
                                catch (Exception ex)
                                {
                                    fileErr = true;
                                    msg = ex.Message;
                                }
                            }
                        }
                        else
                        {
                            fileErr = true;
                            msg = "文件错误";
                        }
                    }

                    #endregion

                    #endregion

                    if (fileErr)
                    {
                        //Alert("文件传输错误，请稍后再试");
                        string href = "";
                        if (act == "u")
                        {
                            href = " window.location = '/internals/publics/courseware/Edit.aspx?act=u&id=" + id + "';";
                        }
                        else
                        {
                            href = "history.back();";
                        }
                        //HttpContext.Current.Response.Write(serverPath + "< br/>");
                        //HttpContext.Current.Response.Write(picFilePath + "< br/>");
                        //HttpContext.Current.Response.Write(soundFilePath + "< br/>");
                        ExecuteJS("alert('" + msg + "');" + href);
                    }
                    else
                    {
                        int rst = 0;
                        string href = "";

                        switch (act)
                        {
                            case "n":

                                rst = bll.AddCourseWare(model);
                                href = "/internals/publics/courseware/Edit.aspx?act=n&cid=" + model.CourseID + "&se=" + model.SerialNumber;

                                break;
                            case "u":
                                model.ID = id;
                                int originalSerialNumber = XRequest.GetInt("OriginalSerialNumberTxt", -1);
                                model.OriginalSerialNumber = originalSerialNumber;
                                rst = bll.UpdateCourseWare(model);
                                href = "/internals/publics/courseware/Edit.aspx?act=u&id=" + id;

                                break;
                            default: break;
                        }

                        if (rst > 0)
                        {
                            if (act == "u")
                            {
                                try
                                {
                                    if (!oldPicFilePath.Equals(""))
                                    {
                                        string nohttp_pic = oldPicFilePath.Substring(oldPicFilePath.IndexOf("//") + 2);
                                        File.Delete(serverPath + nohttp_pic.Substring(nohttp_pic.IndexOf("/")));
                                    }
                                    if (!oldSoundFilePath.Equals(""))
                                    {
                                        string nohttp_sound = oldSoundFilePath.Substring(oldSoundFilePath.IndexOf("//") + 2);
                                        File.Delete(serverPath + nohttp_sound.Substring(nohttp_sound.IndexOf("/")));
                                    }
                                    if (!oldVideoFilePath.Equals(""))
                                    {
                                        string nohttp_video = oldVideoFilePath.Substring(oldVideoFilePath.IndexOf("//") + 2);
                                        File.Delete(serverPath + nohttp_video.Substring(nohttp_video.IndexOf("/")));
                                    }
                                }
                                catch (IOException ioe)
                                { }
                                catch (Exception ex)
                                { }
                            }
                            Alert("操作成功");
                            ExecuteJS("window.location = '" + href + "';");
                        }
                        else
                        {
                            Alert("操作失败");
                            try
                            {
                                File.Delete(picFilePath);
                                File.Delete(soundFilePath);
                                File.Delete(videoFilePath);
                            }
                            catch (IOException ioe)
                            { }
                            catch (Exception ex)
                            { }
                        }
                    }

                }
            }
            else
            {
                if (id != -1)
                {
                    model = bll.GetCourseWareInfoById(id);
                }
                else
                { }
            }
        }

        private bool CheckValue()
        {
            bool rst = true;

            if (XRequest.GetInt("CourseSlt", -1) == -1)
            {
                Alert("请选择课程");
                rst = false;
            }

            if (XRequest.GetInt("SerialNumberTxt", -1) == -1)
            {
                Alert("序号不能为空");
                rst = false;
            }

            if (XRequest.GetString("act") == "u" && XRequest.GetInt("OriginalSerialNumberTxt", -1) == -1)
            {
                Alert("数据加载错误");
                rst = false;
            }

            return rst;
        }

        private string Filter(string str)
        {
            str = str.Replace("\r\n", "\r");
            return str;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}
